#include <fhe/prims/Sim.h>
#include <fhe/core/Registerers.h>
#include <boost/chrono.hpp>

namespace fhe
{
  namespace core
  {
    FHE_NODE( core, Sim );
    FHE_FUNC( core, Sim, run );
    FHE_FUNC( core, Sim, shutdown );
    FHE_VAR( core, Sim, minTime );
    FHE_VAR( core, Sim, maxTime );
    
    Sim::Sim()
      : minTime( 0.01 )
      , maxTime( -1 )
    {
    }
    
    Sim::~Sim()
    {
    }
    
    double Sim::time()
    {
      return boost::chrono::duration<double>( boost::chrono::system_clock::now().time_since_epoch() ).count();
    }
    
    void Sim::run()
    {
      shutdown_ = false;
      double start = time();
      double last = start;
      double now;
      while ( !shutdown_ && ( maxTime <= 0 || last - start < maxTime ) )
      {
        do
        {
          now = time();
        } while ( minTime > 0 && now - last < minTime );
        double dt = now - last;
        last = now;
        publish( "update", now - start, dt );
      }
    }
    
    void Sim::shutdown()
    {
      shutdown_ = true;
    }
  }
}
